package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * admin 登录
     * @param adUserDTO
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO adUserDTO) {
        //1. 判断传入参数中账号密码是否为空
        if (StringUtils.isBlank(adUserDTO.getName())||StringUtils.isBlank(adUserDTO.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"账号或密码不能为空");
        }
            //根据传入用户名查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDTO.getName()));
        if (adUser==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码错误");
        }
            //判断用户状态   9为正常用户
        if (9 != adUser.getStatus().intValue()) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //2. 检查密码是否正确
        String password = adUser.getPassword();//密码
        String salt = adUser.getSalt();//盐
        String newPsd = DigestUtils.md5DigestAsHex((adUserDTO.getPassword() + salt).getBytes());
        if (!password.equals(newPsd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误");
        }

        //3. 修改最近登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);

        //4. 颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());

        //5. 返回结果
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);

        return ResponseResult.okResult(map);
    }
}
